package com.hotel.interceptor;

import com.anji.captcha.util.AESUtil;
import com.hotel.domain.SysUser;
import com.hotel.service.SysUserService;
import com.hotel.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 第一种方法：记住我实现，
 * 第二中方法：拦截器：
 */
@Component
public class RememberMeInterceptor implements HandlerInterceptor {
    @Autowired
    private SysUserService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //获取所有cookies的值
        Cookie[] cookies = request.getCookies();
        //迭代cookie
        for(Cookie cookie:cookies){
            //判断是否有remenberMe的cookie，有拦截，没有放行
            if(Constant.REMEMBER_ME_COOKIE_NAME.equals(cookie.getName())){
                //解密
                String[] split = cookie.getValue().split("--");
                String username=AESUtil.aesDecrypt(split[0],Constant.REMEMBER_ME_AES_KEY);
                String password=AESUtil.aesDecrypt(split[1],Constant.REMEMBER_ME_AES_KEY);
                SysUser login1=service.login(username,password);
                if(login1!=null){
                    //登录成功，重定向到首页
                    request.getSession().setAttribute(Constant.LOGIN_USER,login1);
                    response.sendRedirect("/index");
                    return false;
                }
            }
        }
        return true;
    }
}
